<template>
  <div class="salaryWrap">

    <div class="wage-list" ref="wrapper">
      <div class="wage-happy-box">
        <div class="wage-box" v-if="showData == 1" v-for="(item,index) in salaryList" :key="index">

          <div class="wage-desc-box" v-if="item.id"
               @click="querySalaryDetail(item.salaryDetails,item.actualPay,item.time)">
            <div class="wage-con">
              <span class="name">{{item.companyName}}</span>
              <div class="money-box">
                <span class="money">{{item.actualPay}}元</span>
                <span class="detail">明细&nbsp;>></span>
              </div>
            </div>
            <div class="wage-btn">
              <button type="button" class="draw"
                      @click="drawMoney(item.salaryDetails,item.id,item.actualPay,item.title,item.time)"
                      v-if="item.status == 1 && item.actualPay>0">领取
              </button>
              <span class="title" v-else-if="item.status == 1 && item.actualPay <=0">本月不可领取</span>
              <span class="title" v-else>本月已领取</span>
            </div>
          </div>

          <div class="wage-month-box" v-else>{{item.time}}</div>
        </div>
      </div>
    </div>

    <div class="empty-wrap" v-if="showData == 2">
      <div class="empty-box">
        <div class="img-box"><img src="./empty.png" class="empty" onclick="return false"/></div>
        <div class="tip">没有相关数据~</div>
      </div>
    </div>

    <v-dialog v-model="markVal" content="您还未绑定工资卡，请先绑定再领取" cancelText="取消" confirmText="去绑定" @confirm="bindPage"
              @cancel="cancel"></v-dialog>

    <v-dialog v-model="sendVal" content="恭喜您，工资领取成功，赶快发布动态跟好友分享吧~" cancelText="取消" confirmText="发布动态"
              @confirm="pushPage"
              @cancel="cancelPush"></v-dialog>

    <!--工资明细-->
    <div class="wage-shot" ref="imageToFile" id="imageNode">
      <div class="shot-money-box">
        <span class="shot-month">{{month}}</span>
        <span class="shot-money">总计：{{wage}}元</span>
      </div>

      <div class="detail-con">
        <div class="detail-box" v-for="(item,index) in itemList" :key="index"
             v-if="item.split(':')[0].replace(/\s+/g,'').indexOf('姓名') == -1  && item.split(':')[0].replace(/\s+/g,'').indexOf('身份证') == -1 && item.split(':')[0].replace(/\s+/g,'').indexOf('身份證') == -1
             && item.split(':')[0].replace(/\s+/g,'').indexOf('单价') == -1 && item.split(':')[0].replace(/\s+/g,'').indexOf('上月工价') == -1 && item.split(':')[0].replace(/\s+/g,'').indexOf('本月工价') == -1
             && item.split(':')[0].replace(/\s+/g,'').indexOf('單價') == -1 && item.split(':')[0].replace(/\s+/g,'').indexOf('上月工價') == -1 && item.split(':')[0].replace(/\s+/g,'').indexOf('本月工價') == -1">
          <span class="title1">{{item.split(":")[0]}}：</span><span class="title2">{{item.split(":")[1]}}</span>
        </div>
      </div>
    </div>


    <!--领取弹出层-->
    <div class="draw-salary-modal" v-show="showModal">
      <div class="draw-salary-box">
        <span class="title1">领取至</span>
        <span class="title2">银行：{{chargeBankName}}</span>
        <span class="title3">卡号：{{chargeBankNum}}</span>

        <div class="draw-salary">
          <div class="total-box">
            <span class="title4">领取金额：</span><span class="total-money">￥{{wage}}</span>
          </div>
          <div class="decrease-box">
            <span class="title4">手续费：</span><span class="title4">￥{{chargeMoney}}</span>
          </div>
          <div class="gain-box">
            <span class="title4">实际到账：</span><span class="total-money">￥{{intoAccount}}</span>
          </div>
        </div>

        <span class="title5">预计到账时间为2小时内</span>

        <button type="button" class="draw-salary-btn" @click="gainSalary">确定</button>

        <img src="./del.png" class="pic-close" onclick="return false" @click="closeModal"/>
      </div>
    </div>

    <!--微信绑定手机号-->
    <v-phone v-model="showMark" @bindPhone="bindCustomerPhone"></v-phone>
  </div>
</template>

<script>
  import phone from "../../components/phone"
  import {getDeviceRatio, getSessionStore, getUrlKey, setSessionStore, toDecimal} from "../../config/util"
  import {Base64} from 'js-base64';
  import {baseUrl} from "../../config/env"
  import dialog from '../../components/dialog'
  import html2canvas from 'html2canvas'
  import domtoimage from 'dom-to-image'
  import BScroll from 'better-scroll';
  /*获取当前缩放比*/
  const DEVICE_RATIO = getDeviceRatio();
  /**
   *
   * @param threshold 触发事件的阀值，即滑动多少距离触发
   */
  /*上拉配置*/
  const UP_CONFIG = {
    threshold: -80 * DEVICE_RATIO,
  }

  export default {
    inject: ['reload'],
    data() {
      return {
        showData: 0,
        showModal: false,
        userSign: "",
        month: "",
        currentPage: 1,
        PageSize: 20,
        salaryList: [],
        salaryScroll: null,
        noMoreData: false,
        showCalendar: false,
        date: "",
        sendVal: false,
        markVal: false,
        id: "",
        cardType: "",
        wage: "",
        wageDetail: "",
        itemList: [],
        chargeMoney: "",
        chargeBankNum: "",
        chargeBankName: "",
        intoAccount: "",
        showMark: false,
        circleTitle: ""
      }
    },
    mounted() {
      this.openid = getUrlKey("openid"); //微信openid
      this.userName = getUrlKey("userName"); //用户昵称
      this.userUrl = getUrlKey("userUrl"); //用户头像
      this.countentPhone = getUrlKey("countentPhone"); //手机框 0弹出1不弹出

      if (this.openid != "" && this.openid != "null" && this.openid != null) {
        setSessionStore("openid", Base64.encode(this.openid));
      }
      if (this.userName != "" && this.userName != "null" && this.userName != null) {
        this.userName = decodeURI(this.userName);
        setSessionStore("weixin_userName", this.userName);
      }
      if (this.userUrl != "" && this.userUrl != "null" && this.userUrl != null) {
        setSessionStore("weixin_userUrl", this.userUrl);
      }
      this.userSign = Base64.decode(getSessionStore("openid"));
      if (this.countentPhone == "0") {
        this.showMark = true;
      } else {
        this.querySalary();
      }
    },
    methods: {
      screenShot() {
        html2canvas(this.$refs.imageToFile, {
          width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
          height: document.body.scrollHeight
        }).then((canvas) => {// 第一个参数是需要生成截图的元素,第二个是自己需要配置的参数,宽高等
          let url = canvas.toDataURL('image/png');

          if (url == "data:,") {
            let node = document.getElementById('imageNode');
            domtoimage.toPng(node).then((dataUrl) => {
              url = dataUrl;
              setSessionStore("htmlUrl", url);
              this.$router.push({
                path: "/sharecircle",
                query: {"month": this.month, "wage": this.wage, "circle": 5, "circleTitle": this.circleTitle}
              });
            })
          } else {
            setSessionStore("htmlUrl", url);
            this.$router.push({
              path: "/sharecircle",
              query: {"month": this.month, "wage": this.wage, "circle": 5, "circleTitle": this.circleTitle}
            });
          }
        })
      },
      bindCustomerPhone(phone) {//绑定微信客户手机号
        this.$vux.loading.show({
          text: '加载中',
        });
        //绑定微信手机
        this.axios.get(baseUrl + "/wx_user/set_phone?sgin=" + this.userSign + "&phone=" + phone + "&userName=" + this.userName + "&userUrl=" + this.userUrl).then((res) => {
          let resultObj = res.data;
          this.$vux.loading.hide();
          if (resultObj.code == 0 && resultObj.data == 1) {
            this.querySalary();
          } else {
            this.showMark = true;
            this.$vux.toast.text(resultObj.msg, "middle");
          }
        }).catch((error) => {
          this.$vux.loading.hide();
          this.$vux.toast.text("网络异常", "middle");
        });
      },
      querySalary() {//查询工资列表
        this.axios.get(baseUrl + "/billrecord/query_salarylist?sgin=" + this.userSign + "&versionType=2.5" + "&page=" + this.currentPage + "&size=" + this.PageSize).then((res) => {
          let resultObj = res.data;
          if (resultObj.code == 0) {
            if (resultObj.data != null && resultObj.data.length > 0) {
              this.showData = 1;
              this.salaryList = resultObj.data;

              this.$nextTick(() => {
                this.initScroll();
                this.salaryScroll.on('touchEnd', (pos) => {
                  if (Math.abs(Math.round(pos.y)) > Math.abs(Math.round(this.salaryScroll.maxScrollY + 1))) {
                    this.loadMore();
                  }
                });
              });
            } else {
              this.showData = 2;
            }
          } else {
            this.$vux.toast.text(resultObj.msg, "middle");
          }
        }).catch(() => {
          this.$vux.toast.text("网络异常", "middle");
        });
      },
      loadMore() {//加载更多
        if (!this.noMoreData) {
          this.$vux.loading.show({
            text: '加载中',
          });

          setTimeout(() => {
            this.axios.get(baseUrl + "/billrecord/query_salarylist?sgin=" + this.userSign + "&versionType=2.5" + "&page=" + (++this.currentPage) + "&size=" + this.PageSize).then((res) => {
              let resultObj = res.data;
              if (resultObj.code == 0) {
                if (resultObj.data.length > 0) {
                  this.salaryList = this.salaryList.concat(resultObj.data);
                } else {
                  this.noMoreData = true;
                }
                this.$vux.loading.hide();
              } else {
                this.$vux.loading.hide();
                this.$vux.toast.text(resultObj.msg, "middle");
              }
            })
          }, 500)
        }
      },
      querySalaryDetail(salary, totalMoney, month) {//查询工资明细详情
        this.$router.push({
          path: '/salaryDetail',
          query: {"salary": salary, "totalMoney": totalMoney, "month": month}
        });
      },
      cancel() {//取消
        this.markVal = false;
      },
      bindPage() {//去绑定
        this.markVal = false;
        sessionStorage.setItem("salary_sgin", "001188");
        this.$router.push("/bindcard");
      },
      drawMoney(detail, id, money, title, month, e) {//領取
        if (e && e.stopPropagation) {//如果提供了事件对象，则这是一个非IE浏览器,它支持W3C的stopPropagation()方法
          e.stopPropagation();
        } else {
          window.event.cancelBubble = true;//使用IE的方式来取消事件冒泡
        }

        this.axios.get(baseUrl + "/billrecord/query_bankcardwithDraw?sgin=" + this.userSign).then((res) => {//查询绑定工资卡
          let resultObj = res.data;
          if (resultObj.code == 0 && resultObj.data != null) {
            if (resultObj.data.type == 1) { //没有绑定银行卡
              this.markVal = true;
            } else {
              this.wageDetail = detail;
              this.id = id;
              this.wage = toDecimal(money);
              this.circleTitle = title;
              this.month = month;

              this.chargeMoney = toDecimal(resultObj.data.chargeMoney);
              this.chargeBankNum = "**** **** **** " + resultObj.data.bankNumber;
              this.chargeBankName = resultObj.data.bankName;
              this.intoAccount = toDecimal(this.wage - this.chargeMoney);
              this.showModal = true;
            }
          } else {
            this.$vux.toast.text(resultObj.msg, "middle");
          }
        }).catch(() => {
          this.$vux.toast.text("网络异常", "middle");
        });

      },
      cancelPush() {
        this.sendVal = false;
        this.reload();
      },
      pushPage() {//发布圈子
        this.itemList = this.wageDetail.split(";");
        this.$nextTick(() => {
          this.screenShot();
        });
      },
      closeModal() {
        this.showModal = false;
      },
      gainSalary() {
        this.$vux.loading.show({
          text: '加载中',
        });
        this.axios.post(baseUrl + "/billrecord/withdraw_deposit_by_salary?sgin=" + this.userSign + "&id=" + this.id + "&versionType=2.3").then((res) => {
          let resultObj = res.data;
          this.$vux.loading.hide();
          if (resultObj.code == 0) {
            if (resultObj.data == 1) {
              this.showModal = false;
              this.sendVal = true;
            } else {
              this.$vux.toast.text("领取失败，请稍后重试", "middle");
            }
          } else {
            this.$vux.toast.text(resultObj.msg, "middle");
          }
        }).catch(() => {
          this.$vux.loading.hide();
          this.$vux.toast.text("网络异常", "middle");
        });
      },
      initScroll() {//初始化BScroll
        if (!this.salaryScroll) {
          this.salaryScroll = new BScroll(this.$refs.wrapper, {
            probeType: 3,
            deceleration: 0.003,
            bounce: false,
            swipeTime: 2000,
            click: true,
            pullUpLoad: UP_CONFIG
          });
        } else {
          this.salaryScroll.refresh();
        }
      },
      enable() {
        this.salaryScroll && this.salaryScroll.enable()
      },
      refresh() {
        this.salaryScroll && this.salaryScroll.refresh()
      },
      finishPullUp() {
        this.salaryScroll && this.salaryScroll.finishPullUp()
      }
    },
    watch: {
      salaryList() {
        this.$nextTick(() => {
          this.salaryScroll.refresh();
        })
      }
    },
    components: {
      "v-phone": phone,
      "v-dialog": dialog,
      html2canvas,
      domtoimage,
      BScroll
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../assets/stylus/mixin.styl"

  .salaryWrap
    wh(100%, 100%)
    background: f5f5f5
    .wage-list
      wh(100%, auto)
      background: #f5f5f5
      position: fixed
      top: 0
      bottom: 0
      .wage-box
        display: flex
        align-items: center
        wh(100%, auto)
        .wage-desc-box
          display: flex
          align-items: center
          wh(100%, 1.76rem)
          background: rgba(255, 255, 255, 1)
          border-bottom: 0.027rem solid rgba(242, 242, 242, 1)
          .wage-con
            margin-left: 0.32rem
            .name
              size-color(0.4rem, rgba(51, 51, 51, 1))
              font-weight: 500
            .money-box
              margin-top: 0.24rem
              size-color(0.373rem, rgba(60, 175, 255, 1))
              font-weight: 500
          .wage-btn
            margin-left: auto
            margin-right: 0.32rem
            .draw
              text-align: center
              line-height: 0.8rem
              wh(1.6rem, 0.8rem)
              border: 0.027rem solid rgba(60, 175, 255, 1)
              border-radius(0.16rem)
              size-color(0.4rem, rgba(60, 175, 255, 1))
              background: #FFF
            .title
              size-color(0.347rem, rgba(204, 204, 204, 1))
        .wage-month-box
          wh(100%, 0.8rem)
          background: #F5F5F5
          size-color(0.373rem, #999)
          line-height: 0.8rem
          text-align: center
    .empty-wrap
      fj(center, center)
      wh(100%, auto)
      position: fixed
      top: 1.2rem
      left: 0
      right: 0
      bottom: 0
      .empty-box
        width: 4.773rem
        height: auto
        .img-box
          width: 100%
          height: 4.773rem
          .empty
            width: 100%
            height: 100%
        .tip
          display: flex
          justify-content: center
          margin-top: 0.387rem
          font-size: 0.373rem
          color: rgba(68, 68, 68, 1)
    .wage-shot
      position: absolute
      z-index: -2
      top: 0
      wh(100%, 100%)
      background: #f5f5f5
      .shot-money-box
        display: flex
        align-items: center
        margin-bottom: 0.267rem
        wh(100%, 1.6rem)
        background: rgba(255, 255, 255, 1)
        .shot-month
          margin-left: 0.32rem
          size-color(0.427rem, rgba(51, 51, 51, 1))
          font-weight: 500
        .shot-money
          margin-left: auto
          margin-right: 0.32rem
          size-color(0.4rem, rgba(60, 175, 255, 1))
          font-weight: 500
      .detail-con
        wh(100%, auto)
        background: rgba(255, 255, 255, 1)
        .detail-box
          fj(space-between, center)
          margin: 0 auto
          wh(93.6%, 1.106666rem)
          border-bottom: 0.027rem solid rgba(242, 242, 242, 1)
          &:last-child
            border-bottom: none
          .title1
            size-color(0.386666rem, #3CAFFF)
          .title2
            size-color(0.386666rem, #1B1B1B)
    .draw-salary-modal
      position: fixed
      top: 0
      left: 0
      right: 0
      bottom: 0
      z-index: 100
      background-color: rgba(0, 0, 0, 0.5)
      display: flex
      justify-content: center
      .draw-salary-box
        margin-top: 2.653rem
        display: flex
        flex-direction: column
        position: relative
        wh(8rem, 8.853rem)
        background: rgba(255, 255, 255, 1)
        border-radius(0.16rem)
        .title1
          padding-top: 0.64rem
          padding-bottom: 0.64rem
          text-align: center
          size-color(0.48rem, rgba(51, 51, 51, 1))
          font-weight: 500
        .title2, .title3
          margin-left: 0.947rem
          size-color(0.4rem, rgba(102, 102, 102, 1))
        .title3
          padding-top: 0.32rem
          padding-bottom: 0.32rem
        .draw-salary
          display: flex
          flex-direction: column
          margin: 0 auto
          wh(6.933rem, 2.693rem)
          background: rgba(245, 247, 250, 1)
          border-radius(0.133rem)
          .total-box
            padding-top: 0.453rem
            padding-bottom: 0.32rem
            padding-left: 0.4rem
          .decrease-box
            padding-bottom: 0.32rem
            padding-left: 0.4rem
          .gain-box
            padding-left: 0.4rem
          .title4
            size-color(0.4rem, rgba(102, 102, 102, 1))
          .total-money
            size-color(0.4rem, #3CAFFF)
            font-weight: 500
        .title5
          text-align: center
          padding-top: 0.493rem
          padding-bottom: 0.48rem
          size-color(0.373rem, rgba(153, 153, 153, 1))
        .draw-salary-btn
          margin: 0 auto
          wh(6.933rem, 1.067rem)
          background: rgba(60, 175, 255, 1)
          border-radius(0.16rem)
          size-color(0.453rem, rgba(255, 255, 255, 1))
      .pic-close
        position: absolute
        bottom: -1.5rem
        left: 0
        right: 0
        margin: auto
        wh(0.8rem, 0.8rem)
</style>
